from flask import Flask, render_template, Response,request,redirect
from flask import make_response,url_for,abort,session
import os
import hashlib
import receive
import reply

config = {
	'appSecret':"4e22e57346dfa482c27d28326fb46dfe",
	'appId' :'wx2ab2f364a274ed46',
	'token' : 'aaa123'
}
EncodingAESKey = "GYB4u1K5k6gTAc1zPdpMRYcJu1yprwMgaWaVvh2B"
server_url = 'http://mykingdom.natapp1.cc'

psw_dict = {'s':str(123),1:str(1)}

url_not_intercept = ['/validPSW','/','/valid','/article']

app = Flask(__name__)

@app.route('/validPSW',methods=['POST','GET'])
def index():
	if request.method == 'POST':
		username = request.form['username']
		if username=='':
			username = 1
		passwd = request.form["passwd"]
		if psw_dict[username] == passwd:
			session['username'] = username
			return render_template('snow.html')
		else:
			return redirect(url_for('login'))
	else:
		return redirect(url_for('login'))

@app.route('/')
def login():
	return render_template('login.html')

@app.route('/snow',methods=['POST','GET'])
def snow():

    return render_template('snow.html')

@app.route('/porn',methods=['POST','GET'])
def porn():
    return render_template('porn.html')
	
@app.route('/control',methods=['POST','GET'])
def control():
    if request.method == 'POST':
        cmd = request.form['cmd']
        return render_template('template.html',cmd=cmd)
    else:
        return redirect(url_for('index'))

@app.route('/article',methods=['POST','GET'])
def article():
	title = "this is a title"
	content = "I am content"
	return render_template("article_template.html",title=title,content = content)

# @app.errorhandler(404)
# def not_found(error):
#     resp = make_response(render_template('error.html'), 404)
#     resp.headers['X-Something'] = 'A value'
#     return resp

@app.route('/valid', methods=['GET', 'POST']) #公众号验证
def valid():
	print("valid in")
	if request.method == 'GET':
		print("Get")
		signature = request.args.get("signature")
		timestamp = request.args.get("timestamp")
		nonce = request.args.get("nonce")
		echostr = request.args.get("echostr")
		token = config['token'] #请按照公众平台官网\
		# print(timestamp,nonce,token)

		list = [token, timestamp, nonce]
		print("list:",list)
		list.sort()
		sha1 = hashlib.sha1()
		# print("list:",list)
		# map(sha1.update, list)
		# hashcode = sha1.hexdigest()
		s = list[0] + list[1] + list[2] 
		hashcode= hashlib.sha1(s.encode('utf-8')).hexdigest()
		print ("handle/GET func: hashcode, signature: ", hashcode, signature)

		if hashcode == signature:
			print('hashcode == signature')
			return echostr
		else:
			print("hashcode != signature")
			return ""
	elif request.method == 'POST':
		
		print("post:",request.data)
		webData = request.data
		recMsg = receive.parse_xml(webData)
		if isinstance(recMsg, receive.Msg):
			toUser = recMsg.FromUserName
			fromUser = recMsg.ToUserName
			if recMsg.MsgType == 'text':

				if recMsg.Content==b'1':
					content = "<a href="+ server_url + "></a>"
					replyMsg = reply.TextMsg(toUser, fromUser, content)
					return replyMsg.send()

				elif recMsg.Content==b'p':
					content = "<a href=" +server_url + "/snow>adult</a>"
					replyMsg = reply.TextMsg(toUser, fromUser, content)
					return replyMsg.send()

				elif recMsg.Content == b'2':
					content = server_url + '/'
					replyMsg = reply.TextMsg(toUser, fromUser, content)
					print(replyMsg.send())
					return replyMsg.send()
				# elif recMsg.Content==b'2':
				# 	replyMsg = reply.ImageMsg(toUser, fromUser, '4sXv6U5tRx6wqRbLOZQWAEaYDkrwqF4p7V3DDXbDkFGJKozLpvW85h1o_0NjqJPH')
				# 	return replyMsg.send():

				elif recMsg.Content == b'3':
					replyMsg = reply.ImageTextMsg(toUser,fromUser,"测试","test ImageText send",server_url + "/static/csl.jpg",server_url +"/article")

					return replyMsg.send()
				else:
					print('Msg from user:',recMsg.Content)
					content = "我是要成为海贼王的男人"
					replyMsg = reply.TextMsg(toUser, fromUser, content)
					return replyMsg.send()

			elif recMsg.MsgType == 'image':
				mediaId = recMsg.MediaId
				replyMsg = reply.ImageMsg(toUser, fromUser, mediaId)
				return replyMsg.send()
			else:
				return reply.Msg().send()
		else:
			print ("暂且不处理")
			return "success"
		


@app.before_request
def interceptor():
	request_url = request.path

	if '.jpg' not in request_url and  request_url not in url_not_intercept and 'username' not in session:
		print(request_url +' is intecepted!')
		return redirect(url_for('login'))

def random_secert_key():
    pass

if __name__ == '__main__':
    app.secret_key = os.urandom(24)
    app.run(host='0.0.0.0',
            port = 8080,
            threaded=True)
